<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\SubSettlement;
use App\Models\Settlement;
use App\Models\Freelancer;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\Rule;
use App\Services\FourElement\FourElementVerifier;

class SubSettlementController extends Controller
{
    public function __construct(private readonly FourElementVerifier $fourElementVerifier)
    {
    }
    /**
     * 获取子结算单列表
     */
    public function index(Request $request): JsonResponse
    {
        try {
            $tenantId = $request->user()->tenant_id;
            
            $query = SubSettlement::with(['settlement', 'freelancer'])
                ->where('tenant_id', $tenantId);

            // 按子结算单ID搜索
            if ($request->filled('sub_settlement_id')) {
                $query->where('id', 'like', '%' . $request->sub_settlement_id . '%');
            }

            // 按结算单ID搜索
            if ($request->filled('settlement_id')) {
                $settlementQuery = $request->settlement_id;
                $query->where(function($q) use ($settlementQuery) {
                    $q->where('settlement_id', $settlementQuery)
                      ->orWhereHas('settlement', function($subQ) use ($settlementQuery) {
                          $subQ->where('settlement_number', 'like', '%' . $settlementQuery . '%');
                      });
                });
            }

            // 按姓名搜索
            if ($request->filled('name')) {
                $query->where('freelancer_name', 'like', '%' . $request->name . '%');
            }

            // 按手机号搜索
            if ($request->filled('phone')) {
                $query->where('freelancer_phone', 'like', '%' . $request->phone . '%');
            }

            // 按身份证号搜索
            if ($request->filled('id_card')) {
                $query->where('freelancer_id_card', 'like', '%' . $request->id_card . '%');
            }

            // 按状态筛选
            if ($request->filled('status') && $request->status !== 'all') {
                $query->where('status', $request->status);
            }

            // 按创建时间范围筛选
            if ($request->filled('created_start_date') && $request->filled('created_end_date')) {
                $query->whereBetween('created_at', [
                    $request->created_start_date . ' 00:00:00',
                    $request->created_end_date . ' 23:59:59'
                ]);
            }

            // 按发放时间范围筛选
            if ($request->filled('distributed_start_date') && $request->filled('distributed_end_date')) {
                $query->whereBetween('distributed_at', [
                    $request->distributed_start_date . ' 00:00:00',
                    $request->distributed_end_date . ' 23:59:59'
                ]);
            }

            // 兼容旧的搜索参数
            if ($request->filled('freelancer_keyword')) {
                $query->where(function($q) use ($request) {
                    $q->where('freelancer_name', 'like', '%' . $request->freelancer_keyword . '%')
                      ->orWhere('freelancer_phone', 'like', '%' . $request->freelancer_keyword . '%')
                      ->orWhere('freelancer_id_card', 'like', '%' . $request->freelancer_keyword . '%');
                });
            }

            if ($request->filled('freelancer_id')) {
                $query->where('freelancer_id', $request->freelancer_id);
            }

            if ($request->filled('start_date') && $request->filled('end_date')) {
                $query->whereBetween('created_at', [
                    $request->start_date . ' 00:00:00',
                    $request->end_date . ' 23:59:59'
                ]);
            }

            // 排序
            $sortBy = $request->get('sort_by', 'created_at');
            $sortOrder = $request->get('sort_order', 'desc');
            $query->orderBy($sortBy, $sortOrder);

            // 分页
            $perPage = min($request->get('per_page', 15), 100);
            $page = $request->get('page', 1);
            $subSettlements = $query->paginate($perPage, ['*'], 'page', $page);

            // 格式化数据以匹配前端需求
            $formattedData = $subSettlements->toArray();
            $formattedData['data'] = collect($subSettlements->items())->map(function($item) {
                return [
                    'id' => $item->id,
                    'sub_settlement_id' => $item->id, // 子结算单ID
                    'sub_settlement_number' => $item->sub_settlement_number,
                    'settlement_id' => $item->settlement_id,
                    'settlement_number' => $item->settlement ? $item->settlement->settlement_number : null,
                    'freelancer_id' => $item->freelancer_id,
                    // 自由职业者信息
                    'name' => $item->freelancer_name,
                    'phone' => $item->freelancer_phone,
                    'id_card' => $item->freelancer_id_card,
                    'bank_account' => $item->freelancer_bank_account,
                    'bank_name' => $item->freelancer_bank_name,
                    // 金额信息
                    'commission' => floatval($item->commission),
                    'service_fee' => floatval($item->service_fee),
                    'service_fee_rate' => floatval($item->service_fee_rate),
                    'tax' => floatval($item->tax),
                    'required_balance' => floatval($item->required_balance),
                    'pre_settlement_amount' => floatval($item->pre_settlement_amount),
                    // 状态信息
                    'status' => $item->status,
                    'status_display' => $item->status_display,
                    'status_desc' => $item->status_description,
                    // 其他信息
                    'payment_remarks' => $item->payment_remarks,
                    'electronic_receipt' => $item->electronic_receipt,
                    // 时间信息
                    'created_at' => $item->created_at ? $item->created_at->format('Y-m-d H:i:s') : null,
                    'distributed_at' => $item->distributed_at ? $item->distributed_at->format('Y-m-d H:i:s') : null,
                    'release_time' => $item->distributed_at ? $item->distributed_at->format('Y-m-d H:i:s') : null,
                    // 操作权限
                    'can_edit' => in_array($item->status, [
                        SubSettlement::STATUS_VERIFYING, 
                        SubSettlement::STATUS_VERIFY_FAILED,
                        SubSettlement::STATUS_PENDING_SUBMIT
                    ]),
                    'can_cancel' => !in_array($item->status, [
                        SubSettlement::STATUS_COMPLETED, 
                        SubSettlement::STATUS_CANCELLED, 
                        SubSettlement::STATUS_REFUNDED
                    ]),
                    // 关联数据
                    'settlement' => $item->settlement ? [
                        'id' => $item->settlement->id,
                        'settlement_name' => $item->settlement->settlement_name,
                        'settlement_number' => $item->settlement->settlement_number ?? 'ST' . substr($item->settlement->id, -8)
                    ] : null,
                    'freelancer' => $item->freelancer ? [
                        'id' => $item->freelancer->id,
                        'name' => $item->freelancer->name,
                        'phone' => $item->freelancer->phone,
                        'email' => $item->freelancer->email
                    ] : null
                ];
            })->toArray();

            return response()->json([
                'code' => 0,
                'data' => $formattedData,
                'message' => '获取子结算单列表成功'
            ]);

        } catch (\Exception $e) {
            \Log::error('获取子结算单列表失败', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'request' => $request->all()
            ]);

            return response()->json([
                'success' => false,
                'data' => null,
                'message' => '获取子结算单列表失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 创建子结算单
     */
    public function store(Request $request): JsonResponse
    {
        try {
            $tenantId = $request->user()->tenant_id;

            $validated = $request->validate([
                'settlement_id' => 'required|exists:settlements,id',
                'freelancer_id' => 'required|exists:freelancers,id',
                'pre_settlement_amount' => 'required|numeric|min:0',
                'service_fee_rate' => 'required|numeric|min:0|max:1',
                'payment_remarks' => 'nullable|string|max:1000'
            ]);

            // 验证结算单和自由职业者是否属于当前租户
            $settlement = Settlement::tenant($tenantId)->findOrFail($validated['settlement_id']);
            $freelancer = Freelancer::tenant($tenantId)->findOrFail($validated['freelancer_id']);

            // 检查是否已存在相同的子结算单
            $existing = SubSettlement::query()
                ->tenant($tenantId)
                ->where('settlement_id', $validated['settlement_id'])
                ->where('freelancer_id', $validated['freelancer_id'])
                ->first();

            if ($existing) {
                return response()->json([
                    'success' => false,
                    'data' => null,
                    'message' => '该自由职业者在此结算单中已存在子结算单'
                ], 422);
            }

            // 创建子结算单
            $subSettlement = new SubSettlement($validated);
            $subSettlement->tenant_id = $tenantId;
            $subSettlement->created_by = 1; // TODO: 获取当前用户ID

            // 同步自由职业者信息
            $subSettlement->freelancer_name = $freelancer->name;
            $subSettlement->freelancer_phone = $freelancer->phone;
            $subSettlement->freelancer_id_card = $freelancer->id_card;
            $subSettlement->freelancer_bank_account = $freelancer->bank_account;
            $subSettlement->freelancer_bank_name = $freelancer->bank_name;

            // 计算服务费和佣金
            $subSettlement->calculateServiceFee();

            $subSettlement->save();

            return response()->json([
                'code' => 0,
                'data' => $subSettlement->load(['settlement', 'freelancer']),
                'message' => '创建子结算单成功'
            ]);

        } catch (\Exception $e) {
            \Log::error('创建子结算单失败', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'data' => $request->all()
            ]);

            return response()->json([
                'success' => false,
                'data' => null,
                'message' => '创建子结算单失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 获取子结算单详情
     */
    public function show(Request $request, $id): JsonResponse
    {
        try {
            $tenantId = $request->user()->tenant_id;
            
            $subSettlement = SubSettlement::with(['settlement', 'freelancer'])
                ->tenant($tenantId)
                ->findOrFail($id);

            return response()->json([
                'code' => 0,
                'data' => $subSettlement,
                'message' => '获取子结算单详情成功'
            ]);

        } catch (\Exception $e) {
            \Log::error('获取子结算单详情失败', [
                'id' => $id,
                'error' => $e->getMessage()
            ]);

            return response()->json([
                'success' => false,
                'data' => null,
                'message' => '获取子结算单详情失败：' . $e->getMessage()
            ], 404);
        }
    }

    /**
     * 更新子结算单
     */
    public function update(Request $request, $id): JsonResponse
    {
        try {
            $tenantId = $request->user()->tenant_id;
            
            $subSettlement = SubSettlement::query()->tenant($tenantId)->findOrFail($id);

            if (! in_array($subSettlement->status, [
                SubSettlement::STATUS_VERIFY_FAILED,
            ])) {
                return response()->json([
                    'code' => 422,
                    'message' => '当前状态下不允许编辑银行卡信息',
                    'data' => null,
                ], 422);
            }

            $validated = $request->validate([
                'freelancer_bank_account' => 'required|string|min:8|max:32',
            ]);

            $freelancerName = $subSettlement->freelancer_name ?: ($subSettlement->freelancer->name ?? null);
            $freelancerPhone = $subSettlement->freelancer_phone ?: ($subSettlement->freelancer->phone ?? null);
            $freelancerIdCard = $subSettlement->freelancer_id_card ?: ($subSettlement->freelancer->id_card ?? null);

            if (! $freelancerName || ! $freelancerPhone || ! $freelancerIdCard) {
                return response()->json([
                    'code' => 422,
                    'message' => '缺少四要素所需信息，无法校验银行卡',
                    'data' => null,
                ], 422);
            }

            $verifyResult = $this->fourElementVerifier->verify(
                $freelancerName,
                $freelancerPhone,
                $freelancerIdCard,
                $validated['freelancer_bank_account']
            );

            if (! $verifyResult->passed) {
                return response()->json([
                    'code' => 422,
                    'message' => $verifyResult->message ?? '银行卡四要素校验失败',
                    'data' => [
                        'four_element_code' => $verifyResult->code ?? null,
                        'context' => $verifyResult->context ?? null,
                    ],
                ], 422);
            }

            $subSettlement->freelancer_bank_account = $validated['freelancer_bank_account'];
            $subSettlement->status = SubSettlement::STATUS_PENDING_TAX;
            $subSettlement->save();

            if ($subSettlement->freelancer) {
                $subSettlement->freelancer->bank_account = $validated['freelancer_bank_account'];
                $subSettlement->freelancer->save();
            }

            if ($subSettlement->settlement) {
                $allValidated = ! $subSettlement->settlement
                    ->subSettlements()
                    ->where('status', '!=', SubSettlement::STATUS_PENDING_TAX)
                    ->where('status', '!=', SubSettlement::STATUS_COMPLETED)
                    ->exists();

                if ($allValidated) {
                    $subSettlement->settlement->status = Settlement::STATUS_PENDING_TAX;
                    $subSettlement->settlement->save();
                }
            }

            return response()->json([
                'code' => 0,
                'data' => $subSettlement->load(['settlement', 'freelancer']),
                'message' => '更新子结算单成功'
            ]);

        } catch (\Exception $e) {
            \Log::error('更新子结算单失败', [
                'id' => $id,
                'error' => $e->getMessage(),
                'data' => $request->all()
            ]);

            return response()->json([
                'code' => 500,
                'message' => '更新子结算单失败：' . $e->getMessage(),
                'data' => null,
            ], 500);
        }
    }

    /**
     * 删除子结算单
     */
    public function destroy(Request $request, $id): JsonResponse
    {
        try {
            $tenantId = $request->user()->tenant_id;
            
            $subSettlement = SubSettlement::query()->tenant($tenantId)->findOrFail($id);

            $blockedStatuses = [
                SubSettlement::STATUS_PENDING_DISTRIBUTE,
                SubSettlement::STATUS_DISTRIBUTING,
                SubSettlement::STATUS_COMPLETED,
                SubSettlement::STATUS_REFUNDED,
            ];

            if (in_array($subSettlement->status, $blockedStatuses, true)) {
                return response()->json([
                    'success' => false,
                    'data' => null,
                    'message' => '当前状态下不允许删除'
                ], 422);
            }

            $subSettlement->delete();

            return response()->json([
                'code' => 0,
                'data' => null,
                'message' => '删除子结算单成功'
            ]);

        } catch (\Exception $e) {
            \Log::error('删除子结算单失败', [
                'id' => $id,
                'error' => $e->getMessage()
            ]);

            return response()->json([
                'success' => false,
                'data' => null,
                'message' => '删除子结算单失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 验证子结算单
     */
    public function verify(Request $request, $id): JsonResponse
    {
        try {
            $tenantId = $request->user()->tenant_id;
            
            $subSettlement = SubSettlement::query()->tenant($tenantId)->findOrFail($id);

            $validated = $request->validate([
                'action' => 'required|in:pass,fail',
                'remarks' => 'nullable|string|max:500'
            ]);

            $verifiedBy = 1; // TODO: 获取当前用户ID
            
            if ($validated['action'] === 'pass') {
                $success = $subSettlement->verify($verifiedBy, $validated['remarks']);
                $message = $success ? '验证通过' : '验证失败';
            } else {
                $success = $subSettlement->verifyFailed($verifiedBy, $validated['remarks'] ?? '验证不通过');
                $message = $success ? '验证拒绝' : '操作失败';
            }

            return response()->json([
                'success' => $success,
                'data' => $success ? $subSettlement->fresh(['settlement', 'freelancer']) : null,
                'message' => $message
            ]);

        } catch (\Exception $e) {
            \Log::error('验证子结算单失败', [
                'id' => $id,
                'error' => $e->getMessage(),
                'data' => $request->all()
            ]);

            return response()->json([
                'success' => false,
                'data' => null,
                'message' => '验证操作失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 提交子结算单
     */
    public function submit(Request $request, $id): JsonResponse
    {
        try {
            $tenantId = $request->user()->tenant_id;
            
            $subSettlement = SubSettlement::query()->tenant($tenantId)->findOrFail($id);
            $submittedBy = 1; // TODO: 获取当前用户ID

            $success = $subSettlement->submit($submittedBy);

            return response()->json([
                'success' => $success,
                'data' => $success ? $subSettlement->fresh(['settlement', 'freelancer']) : null,
                'message' => $success ? '提交成功' : '提交失败'
            ]);

        } catch (\Exception $e) {
            \Log::error('提交子结算单失败', [
                'id' => $id,
                'error' => $e->getMessage()
            ]);

            return response()->json([
                'success' => false,
                'data' => null,
                'message' => '提交失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 发放操作
     */
    public function distribute(Request $request, $id): JsonResponse
    {
        try {
            $tenantId = $request->user()->tenant_id;
            
            $subSettlement = SubSettlement::query()->tenant($tenantId)->findOrFail($id);

            $validated = $request->validate([
                'action' => 'required|in:start,complete,fail',
                'electronic_receipt' => 'nullable|array',
                'remarks' => 'nullable|string|max:500'
            ]);

            $distributedBy = 1; // TODO: 获取当前用户ID
            $success = false;
            $message = '';

            switch ($validated['action']) {
                case 'start':
                    $success = $subSettlement->startDistribute($distributedBy);
                    $message = $success ? '开始发放' : '操作失败';
                    break;
                    
                case 'complete':
                    $success = $subSettlement->completeDistribute(
                        $distributedBy, 
                        $validated['electronic_receipt'] ?? null
                    );
                    $message = $success ? '发放完成' : '操作失败';
                    break;
                    
                case 'fail':
                    $success = $subSettlement->distributeFailed(
                        $distributedBy, 
                        $validated['remarks'] ?? '发放失败'
                    );
                    $message = $success ? '标记发放失败' : '操作失败';
                    break;
            }

            return response()->json([
                'success' => $success,
                'data' => $success ? $subSettlement->fresh(['settlement', 'freelancer']) : null,
                'message' => $message
            ]);

        } catch (\Exception $e) {
            \Log::error('发放操作失败', [
                'id' => $id,
                'error' => $e->getMessage(),
                'data' => $request->all()
            ]);

            return response()->json([
                'success' => false,
                'data' => null,
                'message' => '发放操作失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 取消子结算单
     */
    public function cancel(Request $request, $id): JsonResponse
    {
        try {
            $tenantId = $request->user()->tenant_id;
            
            $subSettlement = SubSettlement::query()->tenant($tenantId)->findOrFail($id);

            $validated = $request->validate([
                'remarks' => 'nullable|string|max:500'
            ]);

            $cancelledBy = 1; // TODO: 获取当前用户ID
            $success = $subSettlement->cancel($cancelledBy, $validated['remarks'] ?? null);

            return response()->json([
                'success' => $success,
                'data' => $success ? $subSettlement->fresh(['settlement', 'freelancer']) : null,
                'message' => $success ? '取消成功' : '取消失败'
            ]);

        } catch (\Exception $e) {
            \Log::error('取消子结算单失败', [
                'id' => $id,
                'error' => $e->getMessage(),
                'data' => $request->all()
            ]);

            return response()->json([
                'success' => false,
                'data' => null,
                'message' => '取消失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 退票操作
     */
    public function refund(Request $request, $id): JsonResponse
    {
        try {
            $tenantId = $request->user()->tenant_id;
            
            $subSettlement = SubSettlement::query()->tenant($tenantId)->findOrFail($id);

            $validated = $request->validate([
                'remarks' => 'required|string|max:500'
            ]);

            $operatedBy = 1; // TODO: 获取当前用户ID
            $success = $subSettlement->refund($operatedBy, $validated['remarks']);

            return response()->json([
                'success' => $success,
                'data' => $success ? $subSettlement->fresh(['settlement', 'freelancer']) : null,
                'message' => $success ? '退票成功' : '退票失败'
            ]);

        } catch (\Exception $e) {
            \Log::error('退票操作失败', [
                'id' => $id,
                'error' => $e->getMessage(),
                'data' => $request->all()
            ]);

            return response()->json([
                'success' => false,
                'data' => null,
                'message' => '退票失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 批量操作
     */
    public function batchAction(Request $request): JsonResponse
    {
        try {
            $tenantId = $request->user()->tenant_id;

            $validated = $request->validate([
                'action' => 'required|in:verify_pass,verify_fail,submit,cancel,start_distribute',
                'ids' => 'required|array|min:1',
                'ids.*' => 'exists:sub_settlements,id',
                'remarks' => 'nullable|string|max:500'
            ]);

            $subSettlements = SubSettlement::query()
                ->tenant($tenantId)
                ->whereIn('id', $validated['ids'])
                ->get();

            $successCount = 0;
            $operatedBy = 1; // TODO: 获取当前用户ID

            foreach ($subSettlements as $subSettlement) {
                $success = false;
                
                switch ($validated['action']) {
                    case 'verify_pass':
                        $success = $subSettlement->verify($operatedBy, $validated['remarks'] ?? null);
                        break;
                    case 'verify_fail':
                        $success = $subSettlement->verifyFailed($operatedBy, $validated['remarks'] ?? '批量验证失败');
                        break;
                    case 'submit':
                        $success = $subSettlement->submit($operatedBy);
                        break;
                    case 'cancel':
                        $success = $subSettlement->cancel($operatedBy, $validated['remarks'] ?? null);
                        break;
                    case 'start_distribute':
                        $success = $subSettlement->startDistribute($operatedBy);
                        break;
                }
                
                if ($success) {
                    $successCount++;
                }
            }

            return response()->json([
                'code' => 0,
                'data' => [
                    'total' => count($validated['ids']),
                    'success_count' => $successCount,
                    'failed_count' => count($validated['ids']) - $successCount
                ],
                'message' => "批量操作完成，成功 {$successCount} 条，失败 " . (count($validated['ids']) - $successCount) . " 条"
            ]);

        } catch (\Exception $e) {
            \Log::error('批量操作失败', [
                'error' => $e->getMessage(),
                'data' => $request->all()
            ]);

            return response()->json([
                'success' => false,
                'data' => null,
                'message' => '批量操作失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 获取状态选项
     */
    public function getStatusOptions(): JsonResponse
    {
        return response()->json([
            'success' => true,
            'data' => SubSettlement::getStatusOptions(),
            'message' => '获取状态选项成功'
        ]);
    }

    /**
     * 获取统计信息
     */
    public function getStatistics(Request $request): JsonResponse
    {
        try {
            $tenantId = $request->user()->tenant_id;
            
            $query = SubSettlement::query()->tenant($tenantId);

            // 按结算单筛选
            if ($request->filled('settlement_id')) {
                $query->bySettlement($request->settlement_id);
            }

            $statistics = [
                'total_count' => (clone $query)->count(),
                'total_amount' => (clone $query)->sum('commission'),
                'status_counts' => (clone $query)
                    ->selectRaw('status, count(*) as count, sum(commission) as amount')
                    ->groupBy('status')
                    ->get()
                    ->mapWithKeys(function($item) {
                        return [$item->status => [
                            'count' => $item->count,
                            'amount' => $item->amount,
                            'display' => SubSettlement::getStatusOptions()[$item->status] ?? $item->status
                        ]];
                    })
            ];

            return response()->json([
                'code' => 0,
                'data' => $statistics,
                'message' => '获取统计信息成功'
            ]);

        } catch (\Exception $e) {
            \Log::error('获取统计信息失败', [
                'error' => $e->getMessage()
            ]);

            return response()->json([
                'success' => false,
                'data' => null,
                'message' => '获取统计信息失败：' . $e->getMessage()
            ], 500);
        }
    }
}
